package org.rambadger.command.providers;

import com.sun.jersey.core.spi.component.ComponentContext;
import com.sun.jersey.core.spi.component.ComponentScope;
import com.sun.jersey.spi.inject.Injectable;
import com.sun.jersey.spi.inject.InjectableProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.lang.reflect.Type;

/**
 * Jersey provider that traverses the properties of an object provided by the constructor, to find the value at the path given in the {@link ConfigParam annotation}.
 *
 * Used to inject values from the configuration file.
 */
public class ConfigProvider implements InjectableProvider<ConfigParam, Type> {
    private static final Logger LOGGER = LoggerFactory.getLogger(ConfigProvider.class);
    private Object conf;

    /**
     * Instantiates a new ConfigProvider based on the given object.
     *
     * @param configObject the config object
     */
    public ConfigProvider(Object configObject) {
        this.conf = configObject;
    }

    @Override
    public ComponentScope getScope() {
        return ComponentScope.Singleton;
    }

    @Override
    public Injectable getInjectable(ComponentContext ic, ConfigParam configParam, Type type) {
        String[] path = configParam.value().split("\\.");

        Object current = conf;
        int index = 0;
        try {
            for (index = 0; index < path.length; index++) {
                current = getFieldValue(current, path[index]);
            }
            final Object found = current;
            return new Injectable<Object>() {
                @Override
                public Object getValue() {
                    return found;
                }
            };
        } catch (IllegalAccessException|NoSuchFieldException|NullPointerException e) {
            LOGGER.error("Configuration object traversal failed at part %d '%s' of the path '%s'", index, path[index], configParam.value(), e);
            e.printStackTrace();
            return null;
        }
    }

    /**
     * Retrieves the value of a field from an object.
     *
     * @param obj the object to retrieve the field from
     * @param name name of the internal field being retrieved
     * @return the Object value in that field name
     * @throws NoSuchFieldException
     * @throws IllegalAccessException
     */
    private static Object getFieldValue(Object obj, String name) throws NoSuchFieldException, IllegalAccessException {
        Class klass = obj.getClass();
        Field field = klass.getDeclaredField(name);
        field.setAccessible(true);
        return field.get(obj);
    }
}